"use strict";
const common_vendor = require("../../common/vendor.js");
const common_assets = require("../../common/assets.js");
const utils_api = require("../../utils/api.js");
const { config } = require("../../utils/config.js");
if (!Array) {
  const _easycom_qiun_data_charts2 = common_vendor.resolveComponent("qiun-data-charts");
  _easycom_qiun_data_charts2();
}
const _easycom_qiun_data_charts = () => "../../uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.js";
if (!Math) {
  _easycom_qiun_data_charts();
}
const _sfc_main = {
  __name: "list",
  setup(__props) {
    const transformChartData = (echartsData) => {
      return {
        categories: echartsData.xAxis.data,
        series: echartsData.series
      };
    };
    const opts = {
      type: "line",
      canvasId: "charts",
      canvas2d: true,
      background: "#FFFFFF",
      animation: true,
      timing: "easeOut",
      duration: 1e3,
      padding: [15, 15, 10, 15],
      legend: {
        show: true
      },
      xAxis: {
        disableGrid: true,
        axisLine: true,
        axisLineColor: "#CCCCCC",
        title: "科目"
      },
      yAxis: {
        gridType: "dash",
        dashLength: 2,
        data: [{
          min: 0,
          max: 100,
          title: "分数"
        }]
      },
      extra: {
        line: {
          type: "straight",
          width: 2,
          activeType: "hollow"
        }
      }
    };
    const formData = common_vendor.ref({
      goal: "",
      name: "",
      chartType: "line",
      file: null
    });
    const chartTypes = ["折线图", "柱状图", "饼图", "雷达图", "散点图"];
    const typeIndex = common_vendor.ref(0);
    const handleTypeChange = (e) => {
      typeIndex.value = e.detail.value;
      const types = ["line", "bar", "pie"];
      formData.value.chartType = types[typeIndex.value];
    };
    const chooseFile = async () => {
      try {
        const res = await common_vendor.index.chooseMessageFile({
          count: 1,
          type: 'file',
          extension: ['.xlsx', '.csv']
        });
        
        if (res.tempFiles && res.tempFiles.length > 0) {
          formData.value.file = res.tempFiles[0];
          const fileName = res.tempFiles[0].name || '';
          const fileExt = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
          
          if (!['.xlsx', '.csv'].includes(fileExt)) {
            common_vendor.index.showToast({
              title: '请选择 Excel 或 CSV 文件',
              icon: 'none'
            });
            formData.value.file = null;
            return;
          }
        }
      } catch (error) {
        console.error("选择文件失败:", error);
        common_vendor.index.showToast({
          title: '选择文件失败',
          icon: 'none'
        });
      }
    };
    const canSubmit = common_vendor.computed(() => {
      return formData.value.goal && formData.value.file;
    });
    const aiChartData = common_vendor.ref(null);
    const analysisResult = common_vendor.ref("");
    const loading = common_vendor.ref(false);
    const showLogin = common_vendor.ref(false);
    const handleSubmit = async () => {
      if (!canSubmit.value || loading.value) return;
      loading.value = true;
      
      try {
        const cookie = common_vendor.index.getStorageSync('cookie');
        if (!cookie) {
          throw new Error('未登录');
        }

        const res = await common_vendor.index.uploadFile({
          url: `${config.baseURL}/api/chart/gen`,
          filePath: formData.value.file.path,
          name: "file",
          header: {
            'Cookie': cookie
          },
          formData: {
            goal: formData.value.goal,
            name: formData.value.name,
            chartType: formData.value.chartType
          }
        });

        if (res.statusCode === 200) {
          const result = JSON.parse(res.data);
          if (result.code === 0) {
            aiChartData.value = JSON.parse(result.data.genchart);
            analysisResult.value = result.data.genresult;
            common_vendor.index.showToast({
              title: "分析成功",
              icon: "success"
            });
            handleReset();
          } else {
            throw new Error(result.message || "分析失败");
          }
        }
      } catch (error) {
        console.error("提交失败:", error);
        if (error.message === '未登录') {
          showLogin.value = true;
        } else {
          common_vendor.index.showToast({
            title: error.message || "分析失败",
            icon: "error"
          });
        }
      } finally {
        loading.value = false;
      }
    };
    const handleReset = () => {
      formData.value = {
        goal: "",
        name: "",
        chartType: "line",
        file: null
      };
      typeIndex.value = 0;
    };
    const watchStats = common_vendor.ref([]);
    const totalDuration = common_vendor.ref("0分钟");
    const watchChartData = common_vendor.ref({
      categories: [],
      series: []
    });
    const loadWatchStats = async () => {
      try {
        const res = await utils_api.courseApi.getWatchStats();
        if (res.code === 0 && res.data) {
          watchStats.value = res.data.map((item) => ({
            ...item,
            totalDuration: parseInt(item.totalDuration),
            formattedDuration: item.formattedDuration
          }));
          const totalSeconds = watchStats.value.reduce((sum, item) => {
            return sum + parseInt(item.totalDuration || 0);
          }, 0);
          totalDuration.value = formatDurationFromSeconds(totalSeconds);
          watchChartData.value = {
            categories: watchStats.value.map((item) => item.courseName),
            series: [{
              name: "学习时长",
              // 将秒转换为分钟，四舍五入到1位小数
              data: watchStats.value.map(
                (item) => Math.round(parseInt(item.totalDuration || 0) / 60 * 10) / 10
              )
            }]
          };
        }
      } catch (error) {
        console.error("获取观看统计失败:", error);
        common_vendor.index.showToast({
          title: "获取数据失败",
          icon: "none"
        });
      }
    };
    const formatDurationFromSeconds = (totalSeconds) => {
      if (!totalSeconds || totalSeconds <= 0)
        return "0分钟";
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor(totalSeconds % 3600 / 60);
      const seconds = totalSeconds % 60;
      if (hours > 0) {
        return `${hours}小时${minutes > 0 ? minutes + "分钟" : ""}`;
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds > 0 ? seconds + "秒" : ""}`;
      } else {
        return `${seconds}秒`;
      }
    };
    const goToCourseDetail = (courseId) => {
      common_vendor.index.navigateTo({
        url: `/pages/course/detail?id=${courseId}`
      });
    };
    common_vendor.onMounted(() => {
      loadWatchStats();
    });
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.t(totalDuration.value),
        b: common_vendor.t(watchStats.value.length),
        c: common_vendor.f(watchStats.value, (item, index, i0) => {
          return {
            a: common_vendor.t(item.courseName),
            b: common_vendor.t(item.watchCount),
            c: common_vendor.t(item.formattedDuration),
            d: index,
            e: common_vendor.o(($event) => goToCourseDetail(item.courseId), index)
          };
        }),
        d: watchStats.value.length === 0
      }, watchStats.value.length === 0 ? {
        e: common_assets._imports_0$1
      } : {}, {
        f: formData.value.goal,
        g: common_vendor.o(($event) => formData.value.goal = $event.detail.value),
        h: formData.value.name,
        i: common_vendor.o(($event) => formData.value.name = $event.detail.value),
        j: common_vendor.t(chartTypes[typeIndex.value]),
        k: common_vendor.o(handleTypeChange),
        l: typeIndex.value,
        m: chartTypes,
        n: common_vendor.o(chooseFile),
        o: formData.value.file
      }, formData.value.file ? {
        p: common_vendor.t(formData.value.file.name)
      } : {}, {
        q: common_vendor.t(loading.value ? "分析中..." : "提交分析"),
        r: common_vendor.o(handleSubmit),
        s: !canSubmit.value || loading.value,
        t: loading.value,
        v: common_vendor.o(handleReset),
        w: aiChartData.value
      }, aiChartData.value ? {
        x: common_vendor.p({
          type: aiChartData.value.series[0].type,
          opts,
          chartData: transformChartData(aiChartData.value),
          canvas2d: true,
          canvasId: "ai-charts"
        })
      } : {}, {
        y: analysisResult.value
      }, analysisResult.value ? {
        z: common_vendor.t(analysisResult.value)
      } : {}, {
        showLogin
      });
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-4607d616"]]);
wx.createPage(MiniProgramPage);
